<template>
  <div id="app" class="app-container" :style="backgroundStyle">
    <!-- 全局加载状态 -->
    <div v-if="loading" class="global-loading">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <p>加载中...</p>
    </div>
    
    <template v-else>
      <!-- 主内容区 -->
      <div class="main-content">
        <div class="container">
          <router-view v-slot="{ Component }">
            <transition 
              name="fade" 
              mode="out-in"
              appear
              @before-enter="onBeforeEnter"
              @enter="onEnter"
              @after-enter="onAfterEnter"
            >
              <keep-alive :include="['Home', 'ArticleList']">
                <component :is="Component" :key="$route.fullPath" />
              </keep-alive>
            </transition>
          </router-view>
        </div>
      </div>
    </template>
    
    <!-- 回到顶部 -->
    <el-backtop :right="30" :bottom="30">
      <div class="backtop-inner">
        <el-icon><Top /></el-icon>
      </div>
    </el-backtop>
    
    <!-- 全局通知弹窗 -->
    <el-dialog
      v-model="showAnnouncement"
      title="系统公告"
      width="500px"
      center
      draggable
    >
      <div class="announcement-content" v-html="announcementContent"></div>
      <template #footer>
        <div class="dialog-footer">
          <el-checkbox v-model="dontShowAgain" label="不再显示" size="small" />
          <el-button @click="closeAnnouncement" type="primary">我知道了</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import gsap from 'gsap'

// 导入背景图片
import backgroundImage from '@/assets/images/bg.jpg'

export default {
  name: 'App',
  components: {
  },
  setup() {
    const store = useStore()
    
    // 状态
    const loading = ref(true)
    const showAnnouncement = ref(false)
    const announcementContent = ref('')
    const dontShowAgain = ref(false)
    
    // 添加背景样式计算属性
    const backgroundStyle = computed(() => {
      return {
        backgroundImage: `url(${backgroundImage})`,
        backgroundPosition: 'center',
        backgroundSize: 'cover',
        backgroundAttachment: 'fixed'
      };
    });
    
    // 计算属性
    // eslint-disable-next-line no-unused-vars
    const isLoggedIn = computed(() => store.getters.isLoggedIn)
    
    // 生命周期钩子
    onMounted(async () => {
      // 初始化加载
      await initializeApp()
      
      // 延迟一点时间后隐藏加载状态，给一个平滑过渡
      setTimeout(() => {
        loading.value = false
      }, 500)
      
      // 检查是否需要显示公告
      checkForAnnouncements()
    })
    
    // 方法
    const initializeApp = async () => {
      try {
        // 初始化时检查本地存储中的用户信息
        const userInfo = localStorage.getItem('userInfo')
        if (userInfo) {
          store.commit('user/setUserInfo', JSON.parse(userInfo))
          
          // 只有在用户已登录时才获取未读消息数量
          try {
            // 强制获取最新的用户信息，确保头像等数据是最新的
            await store.dispatch('user/getInfo')
            
            await store.dispatch('message/fetchUnreadMessageCount')
          } catch (error) {
            // 如果获取消息失败，可能是权限问题，尝试清除登录状态
            if (error && error.code === 1001) {
              localStorage.removeItem('userInfo');
              localStorage.removeItem('token');
              localStorage.removeItem('isLoggedIn');
            }
          }
        }
        
        try {
          // 获取网站配置信息
          await store.dispatch('fetchSiteConfig')
        } catch (error) {
          // 忽略错误，让应用继续初始化
        }
        
        try {
          // 获取板块信息
          await store.dispatch('fetchAllBoards')
        } catch (error) {
          // 忽略错误，让应用继续初始化
        }
      } catch (error) {
        // 捕获所有初始化过程中的错误，但不阻止应用启动
      }
    }
    
    // 检查是否需要显示公告
    const checkForAnnouncements = () => {
      const lastShown = localStorage.getItem('lastAnnouncementShown')
      const dontShow = localStorage.getItem('dontShowAnnouncement') === 'true'
      
      // 模拟获取公告，实际项目中应该从API获取
      const announcement = {
        id: 'announcement-2023-10-01',
        content: `
          <h3>系统升级通知</h3>
          <p>尊敬的用户：</p>
          <p>我们的论坛系统已经全面升级，新增了以下功能：</p>
          <ul>
            <li>全新UI界面，提供更好的浏览体验</li>
            <li>优化了文章编辑器，支持更多格式</li>
            <li>新增用户间私信功能</li>
            <li>改进了搜索功能，可以精确查找内容</li>
          </ul>
          <p>感谢您的支持！</p>
        `,
        date: '2023-10-01'
      }
      
      // 判断是否需要显示公告
      if (!dontShow && (!lastShown || lastShown !== announcement.id)) {
        announcementContent.value = announcement.content
        showAnnouncement.value = true
        localStorage.setItem('lastAnnouncementShown', announcement.id)
      }
    }
    
    // 关闭公告
    const closeAnnouncement = () => {
      if (dontShowAgain.value) {
        localStorage.setItem('dontShowAnnouncement', 'true')
      }
      showAnnouncement.value = false
    }
    
    // 页面切换动画
    const onBeforeEnter = (el) => {
      gsap.set(el, {
        opacity: 0,
        y: 15
      })
    }
    
    const onEnter = (el, done) => {
      gsap.to(el, {
        opacity: 1,
        y: 0,
        duration: 0.3,
        onComplete: done
      })
    }
    
    const onAfterEnter = () => {
      // 页面加载完成后滚动到顶部
      window.scrollTo({ top: 0, behavior: 'smooth' })
    }
    
    return {
      loading,
      showAnnouncement,
      announcementContent,
      dontShowAgain,
      closeAnnouncement,
      onBeforeEnter,
      onEnter,
      onAfterEnter,
      backgroundStyle
    }
  }
}
</script>

<style>
/* Fix for ResizeObserver loop errors */
body, html {
  overflow-x: hidden;
}

/* Prevent ResizeObserver error with Element Plus components */
.el-table__body-wrapper,
.el-scrollbar__wrap,
.el-select-dropdown__wrap {
  overflow: hidden !important;
}

.app-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.main-content {
  flex-grow: 1;
  padding: var(--space-5) 0;
  background-color: rgba(255, 255, 255, 0.75);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(3px);
  -webkit-backdrop-filter: blur(3px);
}

.global-loading {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: var(--bg-primary);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: var(--z-50);
}

.loading-icon {
  font-size: 3rem;
  color: var(--primary-color);
  animation: spin 1.5s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.backtop-inner {
  height: 100%;
  width: 100%;
  background-color: var(--primary-color);
  box-shadow: var(--shadow-md);
  color: var(--white);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}

.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.announcement-content {
  max-height: 60vh;
  overflow-y: auto;
  padding: var(--space-2);
}

.announcement-content h3 {
  margin-bottom: var(--space-3);
  color: var(--primary-color);
}

.announcement-content ul {
  padding-left: var(--space-4);
  margin-bottom: var(--space-3);
}

.announcement-content li {
  margin-bottom: var(--space-2);
}

@media (max-width: 768px) {
  .main-content {
    padding: var(--space-3) 0;
  }
}
</style> 